



import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;


public class AcessImap {
	
	private String host;
	private String port;
	private boolean starttls;
	private Store store;
	
	public AcessImap(){
		this.host = "imap.gmail.com";
		this.port = "993";
		this.starttls = true;
		store = null;
	}
	
	public void conect(String login, String password) throws MessagingException{
		
		if((store != null) && store.isConnected())
			store.close();
		
		Properties props = System.getProperties();
		props.setProperty("mail.imap.host", host);
		props.setProperty("mail.imap.port", port);
		props.setProperty("mail.imap.starttls.enable", String.valueOf(starttls));
		
		Session session = Session.getDefaultInstance(props, null);
		
		store = session.getStore("imaps");
		store.connect(host, login, password);
	}
	
	public Message[] getMessages(String foldername) throws MessagingException{
		if((store == null))
			throw new IllegalStateException("Not connected");
		Folder folder = store.getFolder(foldername);
		folder.open(Folder.READ_ONLY);
		return folder.getMessages();
	}
	
	public boolean isConnected(){
		return store.isConnected();
	}

	public void disconnect() throws MessagingException{
		store.close();
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getPort() {
		return port;
	}

	public void setPort(String port) {
		this.port = port;
	}

	public boolean isStarttls() {
		return starttls;
	}

	public void setStarttls(boolean starttls) {
		this.starttls = starttls;
	}
}
